---
category: Array
created: '2021-03-13'
title: Swap two array items
updated: '2021-10-22'
---

**JavaScript version**

```js swapItems.js
// `i` must be less than `j`
const swapItems = (a, i, j) =>
    (a[i] && a[j] && [...a.slice(0, i), a[j], ...a.slice(i + 1, j), a[i], ...a.slice(j + 1)]) || a;
```

**TypeScript version**

```ts swapItems.ts
const swapItems = <T,_>(a: T[], i: number, j: number): T[] => (a[i] && a[j] && [...a.slice(0, i), a[j], ...a.slice(i + 1, j), a[i], ...a.slice(j + 1)]) || a;
```

**Example**

```js example.js
swapItems([1, 2, 3, 4, 5], 1, 4); // [1, 5, 3, 4, 2]
```
